const fs = require('fs')
const fsSync = require('fs')
const path = require('path')
const iconv = require('iconv-lite')
const logger = require('../utils/logger')

const dicDir = path.join(__dirname, '../../resources/dic')
const coursesDir = path.join(__dirname, '../../resources/courses')
const coursesIndexFile = path.join(coursesDir, 'index.json')

/**
 * 获取课程总句子数
 * @param {number} courseId 课程ID
 * @returns {string} 句子数
 */
function getTotalSentencesInLesson(courseId, lessonId) {
  const coursePath = getCoursePath(courseId)
  const lessonPath = path.join(coursesDir, coursePath, lessonId + '.json')
  const lessonContent = fs.readFileSync(lessonPath, 'utf8')
  const LessonContentJSON = JSON.parse(lessonContent)
  return LessonContentJSON.length
}

/**
 * 获取课程的Lesson数量
 * @param {number} courseId 课程ID
 * @returns {string} Lesson数量
 */
function getTotalLessonsInCourse(courseId) {
  // CourseID对应的CoursePath下的json文件数量
  const coursePath = getCoursePath(courseId)
  const coursePathFull = path.join(coursesDir, coursePath)
  return fs.readdirSync(coursePathFull).filter((file) => file.endsWith('.json')).length
}
// 扫描课程资源目录
async function scanCourses() {
  const tempRecognizedCoursesIndexFile = path.join(coursesDir, 'temp_recognized_courses.json')
  if (fs.existsSync(tempRecognizedCoursesIndexFile)) {
    const content = fs.readFileSync(tempRecognizedCoursesIndexFile, 'utf8')
    return JSON.parse(content)
  }
  try {
    // 首先尝试读取 index.json 文件
    let coursesIndex = []
    try {
      const indexContent = fs.readFileSync(coursesIndexFile, 'utf8')
      coursesIndex = JSON.parse(indexContent)
    } catch (indexError) {
      // 如果 index.json 不存在或解析失败，则记录日志并继续
      console.log('Index file not found or invalid, will scan directories directly:', indexError.message)
    }

    const categories = []
    // 如果 index.json 存在且有效，则使用其中的数据
    if (Array.isArray(coursesIndex) && coursesIndex.length > 0) {
      for (const courseInfo of coursesIndex) {
        const coursePath = path.join(coursesDir, courseInfo.path)
        try {
          // 检查目录是否存在
          const stat = fs.statSync(coursePath)
          if (stat.isDirectory()) {
            // 获取课程中的所有JSON文件来确定课堂数量
            const files = fs.readdirSync(coursePath)
            const jsonFiles = files.filter((file) => file.endsWith('.json'))
            const categoryName = courseInfo.category || '自定义'
            let existCategory = categories.find((category) => category.categoryName === categoryName)
            if (!existCategory) {
              existCategory = {
                categoryName,
                courses: []
              }
              categories.push(existCategory)
            }

            existCategory.courses.push({
              id: courseInfo.id,
              title: courseInfo.title,
              description: courseInfo.description || `包含 ${jsonFiles.length} 课的 ${courseInfo.title}`,
              level: courseInfo.level || 'intermediate',
              category: categoryName,
              isActive: courseInfo.isActive !== undefined ? courseInfo.isActive : true,
              path: courseInfo.path,
              lessonCount: jsonFiles.length
            })
          }
        } catch (statError) {
          logger.log(` ■■■Course directory ${courseInfo.path} not found, skipping`)
          console.log(statError)
          // 如果目录不存在，可以选择从列表中移除或者保持原样
        }
      }
      fs.writeFileSync(tempRecognizedCoursesIndexFile, JSON.stringify(categories, null, 2))
      return categories
    }
    logger.error(' ■■■Course index file not found, scanning courses...')
    return []
  } catch (error) {
    logger.error('■■■Error scanning courses:', error)
    return []
  }
}

// 获取特定课程的所有课时
async function getLessonsForCourse(coursePath) {
  const lessonsDir = path.join(coursesDir, coursePath)
  const lessons = []

  try {
    const files = fs.readdirSync(lessonsDir)
    const jsonFiles = files
      .filter((file) => file.endsWith('.json'))
      .sort((a, b) => {
        const numA = parseInt(a.replace('.json', ''))
        const numB = parseInt(b.replace('.json', ''))
        return numA - numB
      })

    for (let i = 0; i < jsonFiles.length; i++) {
      const jsonFile = jsonFiles[i]
      const lessonNumber = parseInt(jsonFile.replace('.json', ''))

      // 检查是否有对应的MP3文件
      const mp3File = `${lessonNumber}.mp3`
      const mp3Exists = files.includes(mp3File)

      // Read the JSON file to get the first sentence as title
      let lessonTitle = `Lesson ${lessonNumber}`
      let lessonTitleCn = ``
      try {
        const lessonContentPath = path.join(lessonsDir, jsonFile)
        const lessonContent = fs.readFileSync(lessonContentPath, 'utf8')
        const lessonData = JSON.parse(lessonContent)

        // Use the first sentence's English text as the lesson title
        if (lessonData && lessonData.length > 0 && lessonData[0].english) {
          lessonTitle = lessonData[0].english
          lessonTitleCn = lessonData[0].chinese
        }
      } catch (readError) {
        console.error(`Error reading lesson file ${jsonFile}:`, readError)
      }

      lessons.push({
        id: lessonNumber,
        courseId: coursePath,
        title: lessonTitle,
        description: `第 ${lessonNumber} 课, ${lessonTitleCn}`,
        order: lessonNumber,
        textFilePath: jsonFile,
        audioFilePath: mp3Exists ? mp3File : null,
        documentFilePath: null,
        isActive: true
      })
    }

    return lessons
  } catch (error) {
    logger.error('Error getting lessons for course:', error)
    return []
  }
}
/**
 * 获取课程ID
 * @param {string} coursePath 课程路径
 * @returns {number} 课程ID
 */
function getCourseID(coursePath) {
  const coursesInfo = fs.readFileSync(coursesIndexFile, 'utf8')
  const coursesJSONArray = JSON.parse(coursesInfo)
  let courseId = null
  for (let i = 0; i < coursesJSONArray.length; i++) {
    if (coursesJSONArray[i].path === coursePath) {
      courseId = coursesJSONArray[i].id
      break
    }
  }
  return courseId
}
/**
 * 获取课程路径
 * @param {number} courseId 课程ID
 * @returns {string} 课程路径
 */
function getCoursePath(courseId) {
  const coursesInfo = fs.readFileSync(coursesIndexFile, 'utf8')
  const coursesJSONArray = JSON.parse(coursesInfo)
  let coursePath = null
  for (let i = 0; i < coursesJSONArray.length; i++) {
    if (`${coursesJSONArray[i].id}` === `${courseId}`) {
      coursePath = coursesJSONArray[i].path
      break
    }
  }
  return coursePath
}
// 获取特定课时的内容
async function getLessonContent(coursePath, lessonId) {
  const lessonJsonPath = path.join(__dirname, '../../resources/courses', coursePath, `${lessonId}.json`)

  try {
    const content = fs.readFileSync(lessonJsonPath, 'utf8')
    return JSON.parse(content)
  } catch (error) {
    logger.error('Error reading lesson content:', error)
    return []
  }
}

async function getLessonAudio(coursePath, lessonId) {
  const lessonAudioPath = path.join(__dirname, '../../resources/courses', coursePath, `${lessonId}.mp3`)

  try {
    const audio = fs.readFileSync(lessonAudioPath)
    return audio
  } catch (error) {
    logger.error('Error reading lesson audio:', error)
    return null
  }
}

// 音标映射表
const phoneticMapping = {
  stress_marks: {
    5: 'ˈ'
  },
  vowels_short: {
    B: 'ɑ',
    A: 'ə',
    E: 'ə',
    a: 'æ',
    e: 'e',
    I: 'ɪ',
    i: 'ɪ',
    O: 'ɒ',
    o: 'ɒ',
    U: 'ʌ',
    u: 'ʌ'
  },
  vowels_long: {
    eI: 'eɪ',
    aI: 'aɪ',
    OI: 'ɔɪ',
    IE: 'ɪə',
    eE: 'eə',
    UE: 'ʊə',
    Ei: 'eɪ',
    Ai: 'aɪ',
    Oi: 'ɔɪ',
    EI: 'eɪ',
    AI: 'aɪ',
    OI: 'ɔɪ'
  },
  consonants: {
    b: 'b',
    c: 'k',
    d: 'd',
    f: 'f',
    g: 'g',
    h: 'h',
    j: 'dʒ',
    k: 'k',
    l: 'l',
    m: 'm',
    n: 'n',
    p: 'p',
    q: 'kw',
    r: 'r',
    s: 's',
    t: 't',
    v: 'v',
    w: 'w',
    x: 'ks',
    y: 'j',
    z: 'z'
  },
  consonant_clusters: {
    tF: 'tʃ',
    dF: 'dʒ',
    sF: 'ʃ',
    zF: 'ʒ',
    nf: 'ŋf',
    ng: 'ŋ',
    nk: 'ŋk',
    nG: 'ŋg',
    tS: 'tʃ',
    dZ: 'dʒ',
    tSH: 'tʃ',
    dZH: 'dʒ'
  },
  special: {
    F: 'ʃ',
    R: 'ɔ',
    S: 'ʃ',
    Z: 'ʒ',
    v: 'ʒ',
    V: 'ʌ',
    D: 'ð',
    T: 'θ',
    C: 'ç',
    N: 'ŋ',
    Q: 'ʌ',
    W: 'ʍ',
    J: 'ʊ',
    '^': 'ɡ',
    ':': 'ː',
    '@': 'ə',
    3: 'ɜ',
    2: 'ɑ',
    6: 'ɐ'
  },
  modifiers: {
    '(': '(',
    ')': ')',
    '[': '[',
    ']': ']',
    '{': '{',
    '}': '}'
  }
}

// 解码音标
function decodePhonetic(phoneticCode) {
  if (!phoneticCode) return ''

  // 移除CDATA标记等额外内容
  let code = phoneticCode.trim()

  // Handle escaped characters - remove backslashes but keep the following character
  code = code.replace(/\\/g, '')

  // 合并所有映射，优先级：clusters > diphthongs > 其他
  const allMappings = {
    ...phoneticMapping.stress_marks,
    ...phoneticMapping.vowels_short,
    ...phoneticMapping.vowels_long,
    ...phoneticMapping.consonants,
    ...phoneticMapping.special,
    ...phoneticMapping.modifiers,
    ...phoneticMapping.consonant_clusters
  }

  // 按照优先级排序，长的键优先匹配
  const sortedMappings = Object.entries(allMappings).sort((a, b) => b[0].length - a[0].length)

  // 逐字符转换
  let result = ''
  let i = 0
  while (i < code.length) {
    // 尝试匹配最长的键
    let matched = false
    for (const [key, value] of sortedMappings) {
      if (code.substring(i).startsWith(key)) {
        result += value
        i += key.length
        matched = true
        break
      }
    }

    // 如果没有匹配到，保留原字符
    if (!matched) {
      result += code[i]
      i += 1
    }
  }

  // 处理括号内的可选音素
  result = result.replace(/\(([^)]+)\)/g, '($1)')

  // 确保音标以/开头和结尾
  if (!result.startsWith('/')) {
    result = '/' + result
  }
  if (!result.endsWith('/')) {
    result = result + '/'
  }

  return result
}

// 解析XML内容
function parseWordContent(content) {
  const result = {
    word: '',
    phonetic: '',
    meanings: [],
    variations: [],
    idioms: [], // 添加习语字段
    phrases: [] // 添加常用词组字段
  }

  content = content.replace(/&I\{pl\}/g, '[复数]')
  content = content.replace(/&D\{(.*?)\}/g, '[$1]')
  content = content.replace(/&B\{(.*?)\}/g, '[$1]')

  // 提取单词
  const wordMatch = content.match(/<单词[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/单词>/s)
  if (wordMatch) {
    result.word = wordMatch[1]
  }

  // 优先查找dicDir下的word-pron.txt,如果存在，则读取内容作为phonetic
  const dicDir = path.join(__dirname, '../../resources/dic')
  const wordFirstLetter = result.word.charAt(0)
  const wordPronFile = path.join(dicDir, wordFirstLetter, `${result.word}-pron.txt`)
  if (fs.existsSync(wordPronFile)) {
    const pronContent = fs.readFileSync(wordPronFile, 'utf8')
    result.phonetic = pronContent
  }
  // 提取音标
  const phoneticMatch = content.match(/<词典音标[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/词典音标>/s)
  if (!result.phonetic && phoneticMatch) {
    // 否则，使用词典音标作为phonetic
    result.phonetic = decodePhonetic(phoneticMatch[1])
  }

  // 提取基本词义
  const basicMeanings = []
  // 首先检查是否有基本词义部分
  const basicMeaningSection = content.match(/<基本词义[^>]*>([\s\S]*?)<\/基本词义>/s)
  if (basicMeaningSection) {
    const meaningRegex = /<单词项[^>]*>([\s\S]*?)<\/单词项>/g
    let match

    while ((match = meaningRegex.exec(basicMeaningSection[1])) !== null) {
      const itemContent = match[1]
      const meaning = {}

      // 提取词性
      const posMatch = itemContent.match(/<单词词性[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/单词词性>/s)
      if (posMatch) {
        meaning.partOfSpeech = posMatch[1]
      }

      // 提取解释项
      const explanations = []
      const explRegex = /<解释项[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/解释项>/g
      let explMatch

      while ((explMatch = explRegex.exec(itemContent)) !== null) {
        explanations.push(explMatch[1])
      }

      // 提取例句
      const examples = []
      const exampleRegex = /<例句[^>]*>([\s\S]*?)<\/例句>/g
      let exampleMatch

      while ((exampleMatch = exampleRegex.exec(itemContent)) !== null) {
        const exampleContent = exampleMatch[1]
        const example = {}

        const originalMatch = exampleContent.match(/<例句原型[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/例句原型>/s)
        const translationMatch = exampleContent.match(/<例句解释[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/例句解释>/s)

        if (originalMatch) example.original = originalMatch[1]
        if (translationMatch) example.translation = translationMatch[1]

        if (originalMatch || translationMatch) {
          examples.push(example)
        }
      }

      meaning.explanations = explanations
      meaning.examples = examples
      basicMeanings.push(meaning)
    }
  }

  result.meanings = basicMeanings

  // 提取词性变化
  const variationsSection = content.match(/<词性变化[^>]*>([\s\S]*?)<\/词性变化>/s)
  if (variationsSection) {
    const variations = []
    const variationRegex = /<单词项[^>]*>([\s\S]*?)<\/单词项>/g
    let varMatch

    while ((varMatch = variationRegex.exec(variationsSection[1])) !== null) {
      const itemContent = varMatch[1]
      const variation = {}

      const wordFormMatch = itemContent.match(/<单词原型[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/单词原型>/s)
      const posMatch = itemContent.match(/<单词词性[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/单词词性>/s)
      const explMatch = itemContent.match(/<解释项[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/解释项>/s)

      if (wordFormMatch) variation.wordForm = wordFormMatch[1]
      if (posMatch) variation.partOfSpeech = posMatch[1]
      if (explMatch) variation.explanation = explMatch[1]

      variations.push(variation)
    }

    result.variations = variations
  }

  // 提取习语
  const idiomsSection = content.match(/<习惯用语[^>]*>([\s\S]*?)<\/习惯用语>/s)
  if (idiomsSection) {
    const idiomItems = idiomsSection[1].match(/<单词项[^>]*>[\s\S]*?<\/单词项>/g)
    if (idiomItems) {
      idiomItems.forEach((item) => {
        const idiom = {}

        const originalMatch = item.match(/<例句原型[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/例句原型>/s)
        const explanationMatch = item.match(/<解释项[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/解释项>/s)

        if (originalMatch) idiom.original = originalMatch[1]
        if (explanationMatch) idiom.explanation = explanationMatch[1]

        if (originalMatch || explanationMatch) {
          result.idioms.push(idiom)
        }
      })
    }
  }

  // 提取常用词组
  const phrasesSection = content.match(/<常用词组[^>]*>([\s\S]*?)<\/常用词组>/s)
  if (phrasesSection) {
    const phraseItems = phrasesSection[1].match(/<单词项[^>]*>[\s\S]*?<\/单词项>/g)
    if (phraseItems) {
      phraseItems.forEach((item) => {
        const phrase = {}

        // 提取单词原型
        const wordFormMatch = item.match(/<单词原型[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/单词原型>/s)
        if (wordFormMatch) phrase.wordForm = wordFormMatch[1]

        // 提取解释项
        const explanationMatch = item.match(/<解释项[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/解释项>/s)
        if (explanationMatch) phrase.explanation = explanationMatch[1]

        // 提取例句
        const examples = []
        const exampleRegex = /<例句[^>]*>([\s\S]*?)<\/例句>/g
        let exampleMatch

        while ((exampleMatch = exampleRegex.exec(item)) !== null) {
          const exampleContent = exampleMatch[1]
          const example = {}

          const originalMatch = exampleContent.match(/<例句原型[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/例句原型>/s)
          const translationMatch = exampleContent.match(/<例句解释[^>]*>\s*<!\[CDATA\[(.*?)\]\]>\s*<\/例句解释>/s)

          if (originalMatch) example.original = originalMatch[1]
          if (translationMatch) example.translation = translationMatch[1]

          if (originalMatch || translationMatch) {
            examples.push(example)
          }
        }

        phrase.examples = examples

        // 只有当至少有一个字段存在时才添加到结果中
        if (wordFormMatch || explanationMatch || examples.length > 0) {
          result.phrases.push(phrase)
        }
      })
    }
  }

  return result
}

// 扫描词典资源
async function scanDictionary() {
  const words = []

  try {
    // 遍历所有字母目录
    const letterDirs = fs.readdirSync(dicDir)

    for (const letterDir of letterDirs) {
      const letterPath = path.join(dicDir, letterDir)
      const stat = fs.statSync(letterPath)

      // 只处理目录
      if (stat.isDirectory()) {
        const wordFiles = fs.readdirSync(letterPath)

        // 处理每个单词文件
        for (const wordFile of wordFiles) {
          if (wordFile.endsWith('.txt')) {
            const wordName = path.parse(wordFile).name
            words.push(wordName)
          }
        }
      }
    }

    return words
  } catch (error) {
    logger.error('Error scanning dictionary:', error)
    return []
  }
}

// 查找词的基本形式
async function findBaseWord(word) {
  const firstLetter = word.charAt(0).toLowerCase()

  // 检查首字母是否为英文字母
  if (!/[a-z]/.test(firstLetter)) {
    return null
  }

  const letterDir = path.join(dicDir, firstLetter)

  // 检查目录是否存在
  if (!fs.existsSync(letterDir)) {
    return null
  }

  const baseWPath = getWordOrigin(firstLetter, word)
  if (baseWPath) {
    return path.basename(baseWPath, '.txt')
  }

  // 读取目录中的所有文件
  const files = fs.readdirSync(letterDir)

  // 查找匹配的词形变化文件
  for (const file of files) {
    // 检查是否为词形变化文件（包含-的文件）
    if (file.includes('-')) {
      const parts = file.split('-')
      // 如果文件名的前半部分匹配查询词，则返回后半部分（基本形式）
      if (parts.length === 2 && parts[0].toLowerCase() === word.toLowerCase()) {
        return parts[1]
      }
    }
  }

  return null
}

// 通过原型查找单词变体
async function findWordVariants(word) {
  const firstLetter = word.charAt(0).toLowerCase()

  // 检查首字母是否为英文字母
  if (!/[a-z]/.test(firstLetter)) {
    return []
  }

  const letterDir = path.join(dicDir, firstLetter)

  // 检查目录是否存在
  if (!fs.existsSync(letterDir)) {
    return []
  }

  // 读取目录中的所有文件
  const files = fs.readdirSync(letterDir)
  const variants = []

  // 查找匹配的词形变化文件
  for (const file of files) {
    // 检查是否为词形变化文件（包含-的文件）
    if (file.includes('-')) {
      const parts = file.split('-')
      // 如果文件名的后半部分匹配查询词，则添加前半部分（变体形式）
      if (parts.length === 2 && parts[1].toLowerCase() === word.toLowerCase()) {
        variants.push(parts[0])
      }
    }
  }

  return variants
}
async function getPhonetic(word) {
  const details = await getWordDetails(word)
  if (!details) return ''
  return details.phonetic
}
// 获取单词发音
async function getWordPronunciation(word) {
  try {
    const wordFirstLetter = word.charAt(0).toLowerCase()
    const wordPronDir = path.join(__dirname, '../../resources/word-pronunciation')
    const extension = '.mp3'
    const filePath = path.join(wordPronDir, wordFirstLetter, `${word}${extension}`)

    if (fs.existsSync(filePath)) {
      // 读取音频文件并返回base64编码
      const audioBuffer = fs.readFileSync(filePath)
      return audioBuffer.toString('base64')
    } else {
      // 尝试查找词形变化
      console.log('Trying to find base word for:', word, ' get word pronunciation')
      const baseWord = await findBaseWord(word)
      if (baseWord && baseWord !== word) {
        const baseWordFirstLetter = baseWord.charAt(0).toLowerCase()
        const baseWordFilePath = path.join(wordPronDir, baseWordFirstLetter, `${baseWord}${extension}`)

        if (fs.existsSync(baseWordFilePath)) {
          // 读取音频文件并返回base64编码
          const audioBuffer = fs.readFileSync(baseWordFilePath)
          return audioBuffer.toString('base64')
        }
      }
    }
  } catch (error) {
    logger.error('Error fetching pronunciation:', error)
  }
  return null
}

// 获取可能的单词原型
function getWordOrigin(firstLetter, word) {
  // 去掉s、es ing+e,ed,d的原型
  if (word.endsWith('s')) {
    const baseWord = word.slice(0, -1)
    console.log(`s-${word} not found, trying ${baseWord}`)
    const wordPath = path.join(__dirname, '../../resources/dic', firstLetter, `${baseWord}.txt`)
    if (fs.existsSync(wordPath)) {
      return wordPath
    }
  }
  if (word.endsWith('es')) {
    const baseWord = word.slice(0, -2)
    console.log(`es-${word} not found, trying ${baseWord}`)
    const wordPath = path.join(__dirname, '../../resources/dic', firstLetter, `${baseWord}.txt`)
    if (fs.existsSync(wordPath)) {
      return wordPath
    }
  }
  if (word.endsWith('ing')) {
    let baseWord = word.slice(0, -3)
    console.log(`ing-${word} not found, trying ${baseWord}`)
    let pathFile = path.join(__dirname, '../../resources/dic', firstLetter, `${baseWord}.txt`)
    if (!fs.existsSync(pathFile)) {
      baseWord = word.slice(0, -3) + 'e'
      console.log(`ing+e-${word} not found, trying ${baseWord}`)
      pathFile = path.join(__dirname, '../../resources/dic', firstLetter, `${baseWord}.txt`)
      if (fs.existsSync(pathFile)) {
        return pathFile
      }
    } else {
      return pathFile
    }
  }
  if (word.endsWith('d')) {
    const baseWord = word.slice(0, -1)
    console.log(`d-${word} not found, trying ${baseWord}`)
    const wordPath = path.join(__dirname, '../../resources/dic', firstLetter, `${baseWord}.txt`)
    if (fs.existsSync(wordPath)) {
      return wordPath
    }
  }
  if (word.endsWith('ed')) {
    const baseWord = word.slice(0, -2)
    console.log(`ed-${word} not found, trying ${baseWord}`)
    const wordPath = path.join(__dirname, '../../resources/dic', firstLetter, `${baseWord}.txt`)
    if (fs.existsSync(wordPath)) {
      return wordPath
    }
  }
  return null
}
// 获取单词详细信息
async function getWordDetails(word) {
  try {
    const firstLetter = word.charAt(0).toLowerCase()

    // 构建文件路径
    let dicPath = path.join(__dirname, '../../resources/dic', firstLetter, `${word}.txt`)

    // 检查文件是否存在
    if (!fsSync.existsSync(dicPath)) {
      console.log('Trying to find base word for:', word, ' get word details')
      const baseWord = await findBaseWord(word)
      if (!baseWord) {
        console.log(` ${word} not found`)
        return null
      }
      console.log(`${word} not found, trying ${baseWord}`)
      dicPath = path.join(__dirname, '../../resources/dic', firstLetter, `${baseWord}.txt`)
      if (!fsSync.existsSync(dicPath)) {
        return null
      }
    }

    // 尝试不同的编码读取文件
    let content
    try {
      const buffer = fsSync.readFileSync(dicPath)
      content = iconv.decode(buffer, 'gbk')
      // 修复缺失的开头字符
      if (!content.startsWith('<')) {
        content = '<' + content
      }
    } catch (err) {
      throw new Error('Failed to read word file: ' + err.message)
    }

    // 解析内容
    const parsedContent = parseWordContent(content)
    return parsedContent
  } catch (error) {
    logger.error('Error getting word details:', error)
    throw error
  }
}

// 扫描单词发音资源
async function scanWordPronunciations() {
  const wordPronDir = path.join(__dirname, '../../resources/word-pronunciation')
  const pronunciations = []

  try {
    // 检查目录是否存在
    try {
      fs.accessSync(wordPronDir)
    } catch (error) {
      // 目录不存在，返回空数组
      return []
    }

    // 遍历所有发音文件
    const files = fs.readdirSync(wordPronDir, { recursive: true })

    for (const file of files) {
      if (file.endsWith('.wav')) {
        const wordName = path.parse(file).name
        pronunciations.push({
          word: wordName,
          fileName: file,
          path: path.join(wordPronDir, file)
        })
      }
    }

    return pronunciations
  } catch (error) {
    logger.error('Error scanning word pronunciations:', error)
    return []
  }
}

module.exports = {
  scanCourses,
  getLessonsForCourse,
  getLessonContent,
  getLessonAudio,
  scanDictionary,
  getWordDetails,
  scanWordPronunciations,
  getCourseID,
  getCoursePath,
  getTotalSentencesInLesson,
  getTotalLessonsInCourse,
  findBaseWord,
  findWordVariants,
  getWordPronunciation,
  getPhonetic
}
